package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    // 切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoPointCut() {

    }

    /**
     * 前置通知
     */
    @Before("autoPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("自动填充");
        System.out.println(joinPoint);
        // 1.获取当前方法数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class); // 获取注解对象
        OperationType operationType = autoFill.value();
        // 2.获取当前方法参数实例
        Object[] args = joinPoint.getArgs();
        if(args.length == 0 || args == null) {
            return;
        }
        Object obj = args[0];
        // 3.添加公共属性
        LocalDateTime now = LocalDateTime.now();
        Long userId = BaseContext.getCurrentId();
        if(operationType == OperationType.INSERT) {

            try {
                Method setCreateTime = obj.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = obj.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setCreateTime.invoke(obj, now);
                setUpdateTime.invoke(obj, now);
                setCreateUser.invoke(obj, userId);
                setUpdateUser.invoke(obj, userId);
            } catch(Exception e ) {
                e.printStackTrace();
            }
        } else {
            try {
                Method setUpdateTime = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = obj.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(obj, now);
                setUpdateUser.invoke(obj, userId);
            } catch(Exception e ) {
                e.printStackTrace();
            }
        }

    }
}
